package com.my.vote.pst.info;

import com.my.vote.VoteApplication;
import com.my.vote.entity.EUser;
import com.my.vote.entity.EVoteInfo;
import com.my.vote.entity.EVoteItem;
import com.my.vote.entity.EVoteRecord;
import com.my.vote.entity.req.ReqVoteItem;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 功能描述:
 *
 * @author
 * @date 2018/4/12
 */
public class PstVoteInfo extends AbstractPresenter<IPstVoteInfo.IVItem> implements IPstVoteInfo {

    @Override
    public void listPage(final ReqVoteItem req) {

        BmobQuery<EVoteItem> query = new BmobQuery<>();
        query.addWhereEqualTo("voteId", req.getVoteId());
        // 限制最多10条数据结果作为一页
        query.setLimit(10);
        // 忽略前10条数据（即第一页数据结果）
        query.setSkip(10 * req.getNowPage());
        // 根据score字段降序显示数据
        query.order("-voteSize");
        query.findObjects(AppCacheManager.getApplication(), new FindListener<EVoteItem>() {
            @Override
            public void onSuccess(List<EVoteItem> list) {
                if (!list.isEmpty()) {
                    getView().onPageList(req.getNowPage(), list.size() >= 10 ? req.getNowPage() + 1 : req.getNowPage(), list);

                } else {
                    getView().onPageError("No Data!");
                }
            }

            @Override
            public void onError(int i, String s) {
                getView().onPageError("No Data!");
            }
        });


    }

    @Override
    public void getVote(String voteId) {
        getView().showLoading(true);
        BmobQuery<EVoteInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("objectId", voteId);
        query.getObject(AppCacheManager.getApplication(), voteId, new GetListener<EVoteInfo>() {


            @Override
            public void onSuccess(EVoteInfo voteInfo) {
                getView().hideLoading();
                getView().onVoteInfo(voteInfo);
            }

            @Override
            public void onFailure(int i, String s) {
                getView().hideLoading();
                getView().showToast("query no data");
            }
        });
    }

    @Override
    public void voteItem(final EVoteInfo voteInfo, final List<EVoteItem> select) {

        getView().showLoading(true);
        //查询是否已投票
        BmobQuery<EVoteRecord> query = new BmobQuery<>();
        query.addWhereEqualTo("voteId", voteInfo.getObjectId());
        query.findObjects(AppCacheManager.getApplication(), new FindListener<EVoteRecord>() {
            @Override
            public void onSuccess(List<EVoteRecord> list) {
                if (list == null || list.isEmpty()) {
                    addVote(voteInfo, select);
                } else {
                    getView().hideLoading();
                    getView().showToast("Already voted!");
                }
            }

            @Override
            public void onError(int i, String s) {
                getView().hideLoading();
                getView().showToast("Select Vote Fail!");
            }
        });


    }

    private void addVote(final EVoteInfo voteInfo, List<EVoteItem> select) {
        //投票人次
        int votingPersonSize = voteInfo.getVotingPersonSize() + select.size();
        voteInfo.setVotingPersonSize(votingPersonSize);
        voteInfo.update(AppCacheManager.getApplication());

        List<BmobObject> objects = new ArrayList<>(select.size());
        for (EVoteItem item : select) {
            int voteSize = item.getVoteSize() != null ? item.getVoteSize() + 1 : 1;
            item.setVoteSize(voteSize);
        }
        objects.addAll(select);
        new BmobObject().updateBatch(AppCacheManager.getApplication(), objects, new UpdateListener() {
            @Override
            public void onSuccess() {
                getView().hideLoading();
                getView().voteSuccess();
                addRecord(voteInfo);
            }

            @Override
            public void onFailure(int i, String s) {
                getView().showToast("Select Vote Fail!");
            }
        });
    }

    /***
     * 添加投票记录
     * @param voteInf
     */
    private void addRecord(EVoteInfo voteInf) {
        EVoteRecord voteRecord = new EVoteRecord();
        final EUser user = AppCacheManager.newInstance().getCache(VoteApplication.USER, new EUser());
        voteRecord.setUserId(user.getObjectId());
        voteRecord.setVoteId(voteInf.getObjectId());
        voteRecord.save(AppCacheManager.getApplication());
    }
}
